package cn.sdack.go.users.controller;

import cn.sdack.go.common.entities.JsonResult;
import cn.sdack.go.common.entities.users.AuthorityEntity;
import cn.sdack.go.common.entities.users.RoleEntity;
import cn.sdack.go.common.entities.users.UserEntity;
import cn.sdack.go.common.querys.users.RoleQuery;
import cn.sdack.go.users.service.GroupService;
import cn.sdack.go.users.service.UserRoleService;
import cn.sdack.go.users.service.UserService;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author sdack
 * @date 2024/1/9
 */
@RestController
public class UserRoleController {

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private UserService userService;

    @Autowired
    private GroupService groupService;
    /**
     * 为授权服务器提供 token 内容
     *
     * @param account
     * @return
     */
    @GetMapping("/open/.well-known/claims")
    public JSONObject openClaims(@RequestParam("a") String account) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("uid","0");
        jsonObject.put("gid","0");
        jsonObject.put("pid","0");
        jsonObject.put("nickname", "");
        jsonObject.put("username", "");
        jsonObject.put("role", "");
        jsonObject.put("authorities",List.of());
        UserEntity userinfo = userService.userinfo(account);
        if (userinfo != null) {
            jsonObject.put("uid",userinfo.getId().toString());
            jsonObject.put("gid",userinfo.getGid().toString());
            jsonObject.put("pid",userinfo.getPid().toString());
            jsonObject.put("nickname", userinfo.getNickname());
            jsonObject.put("username", userinfo.getUsername());
            jsonObject.put("role", userinfo.getIdentity());
            try {
                List<Long> principal = groupService.getPrincipal(account);
                if (principal.isEmpty()) {
                    principal.add(0L);
                }
                jsonObject.put("agent", principal);
            } catch (Exception e) {}
            try {
                List<AuthorityEntity> authorityEntities = userRoleService.userAuthorityList(userinfo.getGid(),userinfo.getId());
                List<String> list = authorityEntities.stream().map(AuthorityEntity::getCode).collect(Collectors.toList());
                jsonObject.put("authorities",list);
            } catch (Exception e) {}
        }

        return jsonObject;
    }

    /**
     * 用户拥有的权限
     *
     * @param userId
     * @return
     */
    @GetMapping("/userAuthority")
    public JsonResult userAuthority(@RequestParam("uid") Long userId) {
        try {
            UserEntity user = userService.getById(userId);
            List<AuthorityEntity> res = userRoleService.userAuthorityList(user.getGid(),userId);
            return JsonResult.toJson(res);
        } catch (Exception e) {
            String message = e.getMessage().toString();
            if (message.length() > 100) {
                message = message.substring(0, 100);
            }
            return JsonResult.toJson(false, message);
        }
    }

    /**
     * 用户拥有的角色
     *
     * @param userId
     * @return
     */
    @GetMapping("/userRole")
    public JsonResult userRole(@RequestParam("uid") Long userId) {
        try {
            UserEntity user = userService.getById(userId);
            List<RoleEntity> res = userRoleService.userRoleList(user.getGid(),userId);
            return JsonResult.toJson(res);
        } catch (Exception e) {
            String message = e.getMessage().toString();
            if (message.length() > 100) {
                message = message.substring(0, 100);
            }
            return JsonResult.toJson(false, message);
        }
    }

    /**
     * 此角色授予的用户列表
     *
     * @param roleKey
     * @return
     */
    @GetMapping("/role/userList")
    public JsonResult roleUser(@RequestParam("roleKey") String roleKey) {
        try {
            List<UserEntity> res = userRoleService.roleUserList(roleKey);
            return JsonResult.toJson(res);
        } catch (Exception e) {
            String message = e.getMessage().toString();
            if (message.length() > 100) {
                message = message.substring(0, 100);
            }
            return JsonResult.toJson(false, message);
        }
    }


    /**
     * 对用户授予角色
     *
     * @param param
     * @return
     */
    @PostMapping("/user/authority")
    public JsonResult authority(@RequestBody RoleQuery param) {
        if (param.getAuthority() == null || param.getAuthority().isEmpty()) {
            return JsonResult.toJson(false, "角色必须");
        }
        if (param.getId() == null) {
            return JsonResult.toJson(false, "用户 必须");
        }
        try {
            UserEntity userEntity = userService.getById(param.getId());
            userRoleService.authority(userEntity.getGid(),param.getId(), param.getAuthority());
            return JsonResult.toJson(true);
        } catch (Exception e) {
            String message = e.getMessage().toString();
            if (message.length() > 100) {
                message = message.substring(0, 100);
            }
            return JsonResult.toJson(false, message);
        }
    }


}
